package cn.csust.net2.manager.client.module;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.csust.net2.manager.client.Manager;
import cn.csust.net2.manager.client.app.App;
import cn.csust.net2.manager.client.ux.BeanGridPanel;
import cn.csust.net2.manager.shared.po.Student;
import cn.csust.net2.manager.shared.po.VoteAnswer;
import cn.csust.net2.manager.shared.service.VoteManagerService;
import cn.csust.net2.manager.shared.service.VoteService;
import cn.csust.net2.manager.shared.service.VoteServiceAsync;
import cn.csust.net2.manager.shared.util.ClassForNameAble;
import cn.csust.net2.manager.shared.util.Constant;

import com.extjs.gxt.charts.client.Chart;
import com.extjs.gxt.charts.client.event.ChartEvent;
import com.extjs.gxt.charts.client.event.ChartListener;
import com.extjs.gxt.charts.client.model.ChartModel;
import com.extjs.gxt.charts.client.model.axis.XAxis;
import com.extjs.gxt.charts.client.model.axis.YAxis;
import com.extjs.gxt.charts.client.model.charts.BarChart;
import com.extjs.gxt.charts.client.model.charts.BarChart.Bar;
import com.extjs.gxt.charts.client.model.charts.CylinderBarChart;
import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.data.BasePagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.layout.FitData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

@ClassForNameAble
public class Vote extends BaseModule {
	private ContentPanel contentPanel;
	private Chart chart;
	private BeanGridPanel<cn.csust.net2.manager.shared.po.Vote> grid;
	private VoteServiceAsync voteService;
	private Window window;
	private int sizeFlag = 0;

	public Vote() {
		init();
		this.setText("投票");
		this.setId("投票");
		this.setClosable(true);
		this.add(contentPanel, new FitData());
		this.addStyleName("pad-text");
	}

	private void init() {
		voteService = GWT.create(VoteService.class);
		initContentPanel();
	}

	public void initContentPanel() {
		initGrid();
		contentPanel = new ContentPanel(new RowLayout(Orientation.VERTICAL));
		contentPanel.setHeaderVisible(false);
		contentPanel.add(grid, new RowData(1, 1));
	}

	public void initGrid() {
		grid = new BeanGridPanel<cn.csust.net2.manager.shared.po.Vote>(
				new cn.csust.net2.manager.shared.po.Vote(), voteService);
		grid.setToolBar(false);
		grid.setAutoLoad(false);
		grid.createDefault();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put(Constant.BANJI_ID, ((Student)(App.getUser())).getBanji().getBanjiID());
		grid.load(map);
//		grid.getGrid().getSelectionModel().addSelectionChangedListener(
//						new SelectionChangedListener<BeanModel>() {
//							@Override
//							public void selectionChanged(
//									SelectionChangedEvent<BeanModel> se) {
//								cn.csust.net2.manager.shared.po.Vote vote = se.getSelectedItem().getBean();
//								changeVoteWindow(vote);
//								
//							}
//		});
		grid.getGrid().addListener(Events.CellClick, new Listener<BaseEvent>() {

			@Override
			public void handleEvent(BaseEvent be) {
				if(grid.getGrid().getSelectionModel().getSelectedItems().size()!=1){
					MessageBox.alert("警告","请选择一项进行投票",null);
				}
				cn.csust.net2.manager.shared.po.Vote vote  = grid.getGrid().getSelectionModel().getSelectedItem().getBean();
				changeVoteWindow(vote);
			}
		});
	}

	public void changeVoteWindow(cn.csust.net2.manager.shared.po.Vote vote) {
		if (window == null) {
			window = new Window();
			window.setLayoutOnChange(true);
			window.setSize(650, 450);
			window.setBlinkModal(true);
			window.setPlain(true);
			
			window.setModal(true);
			window.setLayout(new FitLayout());
		}
		initchart(vote);
		window.add(chart, new FitData());
		window.show();
	}

	public void initchart(cn.csust.net2.manager.shared.po.Vote vote) {
		if (chart == null) {
			//String url = "../../";
			 String url = !Manager.isExplorer() ? "../../" : "";    
			 url += "gxt/chart/open-flash-chart.swf";
//			System.out.println("执行");
//			String url ="/chart/open-flash-chart.swf";
			chart = new Chart(url);
		}
		loadChart(vote);
	}

	public void loadChart(final cn.csust.net2.manager.shared.po.Vote vote) {
		PagingLoadConfig config = new BasePagingLoadConfig();
		config.set(VoteManagerService.VOTEID, vote.getVoteId());
		if (vote != null) {
			voteService.findVoteAnswersByPaging(config,
					new AsyncCallback<PagingLoadResult<VoteAnswer>>() {
						@Override
						public void onSuccess(
								PagingLoadResult<VoteAnswer> result) {
							List<VoteAnswer> answers = result.getData();
							final Map<VoteAnswer, Integer> resultMap = new LinkedHashMap<VoteAnswer, Integer>();
							sizeFlag = answers.size();
							for (int i = 0; i < answers.size(); i++) {
								final VoteAnswer answer = answers.get(i);
								voteService.findVoteResultsByAnswerID(
										answer.getAnswerId(),
										new AsyncCallback<Integer>() {

											@Override
											public void onFailure(
													Throwable caught) {
												MessageBox
														.alert("警告",
																"获取选票数据失败："
																		+ answer.getText(),
																null);
											}

											@Override
											public void onSuccess(Integer result) {
												resultMap.put(answer, result);
												if (resultMap.size() == sizeFlag) {
													changeChartModel(vote, resultMap);
												}
											}
										});
							}
						}

						@Override
						public void onFailure(Throwable caught) {
							MessageBox.alert("", "get voteanswer failed", null);

						}
					});
		}
	}


	private void changeChartModel(
			final cn.csust.net2.manager.shared.po.Vote vote,
			final Map<VoteAnswer, Integer> resultMap) {
		int step = 10;
		int max = 100;
		for (int num : resultMap.values()) {
			if (num > 100) {
				max = (3 + (num - 100) / 50) * 50;
				step = max / 10;
			}
		}

		final ChartModel chartModel = new ChartModel(vote.getTitle(),
				"font-size: 14px; font-family: Verdana; text-align: center;");
		chartModel.setBackgroundColour("#ffffff");
		final CylinderBarChart bchart = new CylinderBarChart();
		bchart.setColour("#440088");
		bchart.setAlpha(.8f);
		//设置chart的 bar 信息
		String[] lables = new String[resultMap.size()];
		int s = 0;
		for (VoteAnswer an : resultMap.keySet()) {
			Bar bar = new BarChart.Bar(resultMap.get(an));
			bar.setTooltip(an.getText() + " #val#票");
			bar.set(VoteService.VOTEANSWERID, an.getAnswerId());
			bchart.addBars(bar);
			lables[s] = new String(an.getText());
			s++;
		}

		

		// 检查是否有投票权限决定当前用户是否有投票权限
		PagingLoadConfig config = new BasePagingLoadConfig();
		config.set(VoteService.VOTEID, vote.getVoteId());
		config.set(VoteService.STUDENT_NUMBER, App.getUser().getUserID());
		voteService.canVoteByPaging(config, new AsyncCallback<Boolean>() {

			@Override
			public void onSuccess(Boolean result) {
			// 若有投票权限就在barchart上加载listener 给用户投票用	
				if (result == true) {
					bchart.addChartListener(new ChartListener() {
						@Override
						public void chartClick(ChartEvent ce) {
							super.chartClick(ce);
							final Bar b = (Bar) ce.getDataType();
							PagingLoadConfig config = new BasePagingLoadConfig();
							config.set(BaseModule.STUDENT_NUMBER, App.getUser()
									.getUserID());
							config.set(VoteService.VOTEID, vote.getVoteId());
							config.set(VoteService.VOTEANSWERID,
									b.get(VoteService.VOTEANSWERID));
							voteService.saveVoteResultByPaging(config,
									new AsyncCallback<Boolean>() {

										@Override
										public void onFailure(Throwable caught) {
											Info.display("Chart Clicked",
													"投票失败！ ");

										}

										@Override
										public void onSuccess(Boolean result) {
											if (result == true) {
											//	int s = 0;
												for (VoteAnswer an : resultMap
														.keySet()) {
													if (an.getAnswerId() == b
															.get(VoteService.VOTEANSWERID)) {
														resultMap
																.put(an,
																		resultMap
																				.get(an) + 1);
													}
												}
												changeChartModel(vote, resultMap);							
												Info.display("提示", "投票成功. ");
											} else {
												Info.display("提示",
														"本次投票无效。原因：你已经投过票. ");
											}

										}
									});
							Info.display("提示", "正在提交你的投票... ");
						}
					});

					window.hide();
					window.show();
				}

			}

			@Override
			public void onFailure(Throwable caught) {
				Info.display("提示", "获取投票权限失败！ ");
			}
		});
		
		XAxis xa = new XAxis();
		xa.setLabels(lables);
		xa.setZDepth3D(5);
		xa.setTickHeight(4);
		xa.setOffset(true);
		xa.setColour("#909090");
		chartModel.setXAxis(xa);
		YAxis ya = new YAxis();
		ya.setSteps(step);
		ya.setMax(max);
		chartModel.setYAxis(ya);
		chartModel.addChartConfig(bchart);
		chart.setChartModel(chartModel);
	}

}
